package com.example.netty_demo.service;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

/**
 * @author benjamin_5
 * @Description
 * @date 2024/8/30
 */
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 处理客户端请求
        System.out.println("Received message: " + msg);
        // 回复客户端
        try{
            ctx.writeAndFlush("Hello, " + msg + "!\n");
        }catch (Exception e){
            System.out.println("消息回复失败");
            e.printStackTrace();
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

